# --! coding=utf-8 !--
# coding=utf-8
# Copyright (c) [2025] [2578713815@qq.com]
# [AHPU_EQM] is licensed under Mulan PSL v2.
"""
日志管理功能库\n
author: <2578713815@qq.com>\n
"""
import time
from CONFIG import settings
from datetime import datetime


def log_cleaner(file_path: str = settings.LOG_PATH):
	"""
	日志清空线程函数,每7天检查一次，只保存30天的日志信息
	:param file_path:
	:return:
	"""
	while True:
		save_data_list = []
		current_timestamp = int(time.time())
		with open(file_path, "r", encoding="utf-8") as f:
			log = f.readlines()
		if len(log) == 0:
			time.sleep(60 * 60 * 24 * 7)
			continue
		for i in log:
			if len(i) < 5:
				continue
			log_time = i.split("|")[0].strip()
			date_format = "%Y-%m-%d %H:%M:%S"  # 定义日期时间的格式
			dt = datetime.strptime(log_time, date_format)  # 将字符串解析为datetime对象
			timestamp = dt.timestamp()  # 将datetime对象转换为时间戳
			if (current_timestamp - timestamp) <= (60 * 60 * 24 * 30):
				save_data_list.append(i)
		if len(save_data_list) > 0:
			with open(settings.LOG_PATH, "w", encoding="utf-8") as f:
				for i in save_data_list:
					f.write(i)
		time.sleep(60 * 60 * 24 * 7)
